package com.zhny.aiot.xf.weigh.bridge.plugin.device;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.plugin.udc.UdcEngine;
import com.zhny.aiot.plugin.udc.command.IUdcPrivateRequestMessage;
import com.zhny.aiot.plugin.udc.device.UdcDevice;
import com.zhny.aiot.xf.weigh.bridge.plugin.model.WeighBridgeStoreEntry;
import io.netty.buffer.ByteBuf;

public class WeighBridgeDevice extends UdcDevice<WeighBridgeConfig> {
    public WeighBridgeDevice(UdcEngine engine, IDeviceFactory<WeighBridgeConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
    }

    @Override
    protected IUdcPrivateRequestMessage createRequestMessage(TaskEntity taskEntity) {
        return null;
    }

    @Override
    protected void onData(ByteBuf byteBuf) {
        int len = byteBuf.readableBytes();
        if(len == 12){
            logger.info("xf weigh bridge key[{}] value len[{}] ",getConfigKey(),len);
            int header = byteBuf.readUnsignedByte();
            int flag = byteBuf.readUnsignedByte();
            byte[] weigh = new byte[6];
            byteBuf.readBytes(weigh);
            String weighStr = new String(weigh);
            int decimalNo = byteBuf.readUnsignedByte() - 48;
            int crc = byteBuf.readUnsignedShort();
            int last = byteBuf.readUnsignedByte();
            if(header == 2 && last == 03){
                int strLen = weighStr.length();
                if(decimalNo >= strLen){
                    logger.error("xf weigh bridge key[{}] decimalNo[{}] > value[{}] data len "
                            ,getConfigKey(),decimalNo,weighStr);
                    return;
                }


                StringBuilder builder = new StringBuilder(weighStr);
                builder.insert(strLen - decimalNo,".");
                String weighValue = builder.toString();
                logger.info("xf weigh bridge key[{}] value [{}]",getConfigKey(),weighValue);
                WeighBridgeStoreEntry storeEntry = new WeighBridgeStoreEntry();
                storeEntry.setWeight(Double.valueOf(weighValue));
                MessageEntry resultMsg = MessageUtils.createMessageEntry (this.getId ());
                resultMsg.setType(MessageType.RESULT);
                resultMsg.setData(storeEntry);
                save(storeEntry);
                saveReal(storeEntry);
                nofity(resultMsg);
            }
        }
    }

    @Override
    public boolean onCheck(ByteBuf byteBuf) {
        return true;
    }

    @Override
    protected void disposable() {

    }
}
